<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user.js'
import { userGetUserService, userUpdateAvatarService } from '@/api/user.js'
import { ElMessage } from 'element-plus'
const userStore = useUserStore()
const uploadRef = ref()
const imageUrl = ref(userStore.userInfo.user_pic)
const submitUpload = async () => {
  await userUpdateAvatarService(imageUrl.value)
  //   提醒更新成功
  ElMessage.success('更新成功')
  // 跟新store用户信息
  let response = await userGetUserService()
  userStore.setUserInfo(response.data.data)
}
const onImgChange = (file) => {
  // 基于fileReader做图片预览
  const fileReader = new FileReader()
  fileReader.readAsDataURL(file.raw)
  fileReader.onload = (e) => {
    imageUrl.value = e.target.result
  }
}
</script>

<template>
  <PageContainer title="用户头像">
    <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :disabled="true"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="onImgChange"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

      <template #tip>
        <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
      </template>
    </el-upload>
    <el-button type="primary" @click="uploadRef.$el.querySelector('input').click()"
      >select file</el-button
    >
    <el-button class="ml-3" type="success" @click="submitUpload"> upload to server </el-button>
  </PageContainer>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
